<?php

namespace caroltc\jenkinsapp\util;

Class Http
{
    public static function post($path, $fields)
    {
        return self::postJson($path, $fields, 'form');
    }

    public static function postJson($url, $fields=array(), $data_type='json',$method='POST',$app_headers=array())
    {
        // $access_token,
        // $cookies_items=array();
        // $cookies=array(
        // 	'AccessToken'=>$access_token,
        // 	'AccessType'=>'shopadmin',
        // 	);
        //    foreach ($cookies as $key => $value) {
        //    	$cookies_items[]=urlencode($key)."=".urlencode($value);
        //    }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        $headers=array(
            // 'W-ACCESS-TOKEN: '.$access_token,
        );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($data_type== 'json') {
            $data_string = json_encode($fields);
            $headers[] = 'Content-Type: application/json';
            $headers[] = 'Content-Length: ' . strlen($data_string);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
        }

        // addd header
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($headers,$app_headers));

        // curl_setopt($ch, CURLOPT_COOKIE, implode(';', $cookies_items));
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

        if($method=='PUT'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        }elseif($method=='DELETE'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }

        $result = curl_exec($ch);
        if ($result !== false) {
            curl_close($ch);
            static::log($url, $fields, $result);
            return $result;
        }
        $error_msg = curl_error($ch);
        curl_close($ch);
        static::logError($url, $fields, $result, $error_msg);
        throw new \Exception($error_msg);
    }

    public static function get($url, $fields=array())
    {
        //$access_token,
        // $cookies_items=array();
        // $cookies=array(
        // 	'AccessToken'=>$access_token,
        // 	'AccessType'=>'shopadmin',
        // 	);
        //    foreach ($cookies as $key => $value) {
        //    	$cookies_items[]=urlencode($key)."=".urlencode($value);
        //    }

        $curlFields=array();
        if($fields && count($fields)>0){
            foreach ($fields as $key => $value) {
                $curlFields[]=urlencode($key)."=".urlencode($value);
            }
        }
        $curlPost=implode('&', $curlFields);
        if(strlen($curlPost)>0){
            $curlPost="?".$curlPost;
        }else{
            $curlPost="";
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url.$curlPost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            // 'W-ACCESS-TOKEN: '.$access_token
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_POST, 1);
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        // curl_setopt($ch, CURLOPT_COOKIE, implode(';', $cookies_items));
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $result = curl_exec($ch);
        if ($result !== false) {
            curl_close($ch);
            static::log($url, $fields, $result);
            return $result;
        }
        $error_msg = curl_error($ch);
        curl_close($ch);
        static::logError($url, $fields, $result, $error_msg);
        throw new \Exception($error_msg);
    }

    public static function basicAuthGetAndReturnHeader($url, $user_name, $password, $url_params = [], $header = [])
    {
        return static::basicAuth($url, $user_name, $password, 'GET', $url_params, [], 'form', $header, true);
    }

    public static function basicAuthGet($url, $user_name, $password, $url_params = [], $header = [])
    {
        return static::basicAuth($url, $user_name, $password, 'GET', $url_params, [], 'form', $header);
    }

    public static function basicAuthPost($url, $user_name, $password, $url_params = [], $data = [], $header = [])
    {
        return static::basicAuth($url, $user_name, $password, 'POST', $url_params, $data, 'form', $header);
    }

    public static function basicAuthPostJson($url, $user_name, $password, $url_params = [], $data = [], $header = [])
    {
        return static::basicAuth($url, $user_name, $password, 'POST', $url_params, $data, 'json', $header);
    }

    private static function basicAuth($url, $user_name, $password, $type='GET', $url_params = [], $data = [], $data_type='form',$header = [], $return_header = false)
    {
        $ch = curl_init();

        if (!empty($url_params)) {
            curl_setopt($ch, CURLOPT_URL, $url .  '?' . http_build_query($url_params));
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }

        if ($type == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            if ($data_type == 'json') {
                $data_string = json_encode($data);
                $headers[] = 'Content-Type: application/json';
                $headers[] = 'Content-Length: ' . strlen($data_string);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($return_header) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
        }

        curl_setopt($ch,  CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "{$user_name}:{$password}");

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($ch);
        if ($result !== false) {
            if ($return_header) {
                // 获得响应结果里的:头大小
                $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
                // 根据头大小去获取头信息内容
                $header = substr($result, 0, $headerSize);
                $headArr = explode("\r\n", $header);
                $body = substr($result, $headerSize);
                static::log($url, ["u" => $user_name, "p" => $password, 'data' => $data, 'url_params' => $url_params], $result);
                curl_close($ch);
                return ['header' => $headArr, 'body' => $body];
            } else {
                static::log($url, ["u" => $user_name, "p" => $password, 'data' => $data, 'url_params' => $url_params], $result);
                curl_close($ch);
                return $result;
            }
        }
        $error_msg = curl_error($ch);
        curl_close($ch);
        static::logError($url, ["u" => $user_name, "p" => $password, 'data' => $data, 'url_params' => $url_params], $result, $error_msg);
        throw new \Exception($error_msg);
    }


    private static function logError($path, $params, $result, $error)
    {
        $result = nl2br(strip_tags($result)); // 回车转换
        Log::e("[CURL][ERROR] path:{$path}, params:" . json_encode($params) . ", result:" . $result . ", exception: " . $error);
    }

    private static function log($path, $params, $result)
    {
        Log::i("[CURL] path:{$path}, params:" . json_encode($params) . ", result:" . $result);
    }
}